﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CraftParameterConfig.Infrastructure.Common
{
    public class ObjectChange
    {
        public IEnumerable<T> ChangeTableToObject<T>(DataTable dtSource) where T : new()
        {
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                T t = new T();
                Type temp = typeof(T);
                PropertyInfo[] propers = temp.GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (var item in propers)
                {
                    //排除出状态字段
                    if (item.Name == "UpdateType")
                    {
                        continue;
                    }
                    var value = dtSource.Rows[i][item.Name.ToUpper()].ToString();
                    if (item.PropertyType.IsEnum)
                    {
                        object o = Enum.Parse(item.PropertyType, value);
                        item.SetValue(t, o);
                        continue;
                    }
                    switch (item.PropertyType.ToString())
                    {
                        case "System.Int32":
                            item.SetValue(t, Convert.ToInt32(value));
                            break;
                        case "System.DateTime":
                            item.SetValue(t, Convert.ToDateTime(value));
                            break;
                        case "System.Double":
                            item.SetValue(t, Convert.ToDouble(value));
                            break;
                        case "System.Guid":
                            item.SetValue(t, Guid.Parse(value));
                            break;
                        case "System.Boolean":
                            bool r = value == "True";
                            item.SetValue(t, r);
                            break;
                        default:
                            item.SetValue(t, value);
                            break;
                    }
                }
                yield return t;
            }
        }

        public DataTable ChangeListToTable<T>(List<T> source)
        {
            Type temp = typeof(T);
            PropertyInfo[] propers = temp.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            DataTable dtResult = new DataTable();
            foreach (var item in propers)
            {
                dtResult.Columns.Add(item.Name.ToUpper());
            }
            foreach (var item in source)
            {
                DataRow drTemp = dtResult.NewRow();
                foreach (var p in propers)
                {
                    drTemp[p.Name.ToUpper()] = p.GetValue(item).ToString();
                }
                dtResult.Rows.Add(drTemp);
            }
            return dtResult;
        }
    }
}
